<?php

namespace app\common\model\general;

use app\common\model\LihuaToolsConf;
use think\Model;
use traits\model\SoftDelete;


class LihuaCity extends Model
{

    // 表名
    protected $table = 'lihua_city';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    protected function setPayTypesAttr($value)
    {
        return $value && is_array($value) ? json_encode($value) : null;
    }

    // 支付方式
    public static function getPayTypeList()
    {
        return [1 => '支付宝支付', 2 => '微信支付', 3 => '丽华钱包', 4 => '货到付款'];
    }

    // 获取城市数组
    public static function getCityArr()
    {
        return self::where('status',1)->order('weigh','desc')->column('id,name');
    }

    // 获取城市列表
    public static function getCityList()
    {
        return self::all(function ($query) {
            $query->where('status', 1)->field('id,name')->order('weigh', 'desc');
        });
    }

    // 获取城市及门店列表
    public static function getCityAndStoreList()
    {
        $cityList  = self::getCityList();
        $storeList = LihuaStore::where('status', 1)->order('id', 'asc')
            ->field('id,city_id,name,addr,lng,lat')->select();
        $list = [];
        foreach ($storeList as $k => $v) {
            $list[$v['city_id']][] = [
                'id'   => $v['id'],
                'name' => $v['name'],
                'addr' => $v['addr'],
                'lng'  => $v['lng'],
                'lat'  => $v['lat'],
            ];
        }
        foreach ($cityList as $k => $v) {
            $cityList[$k]['store_list'] = isset($list[$v['id']]) ? $list[$v['id']] : [];
        }

        return $cityList;
    }

    // 获取城市信息
    public static function getCityInfo($city_id_or_name = '')
    {
        $info = [];
        if (is_numeric($city_id_or_name)) {
            $row = self::get($city_id_or_name);
        } else {
            $row = self::getByName($city_id_or_name);
        }
        if ($row) {
            $enough = self::getCityEnough($row['id']);
            $info = [
                'city_id'        => $row['id'],
                'city_name'      => $row['name'],
                'am_time'        => [substr($row['am_start'], 0, -3), substr($row['am_end'], 0, -3)],
                'pm_time'        => [substr($row['pm_start'], 0, -3), substr($row['pm_end'], 0, -3)],
                'tel'            => $row['tel'],
                'min_price'      => round($row['min_price'], 2),
                'deliver_fee'    => round($row['deliver_fee'], 2),
                'pay_types'      => $row['pay_types'] ? json_decode($row['pay_types'], true) : [],
                'notice'         => $row['notice'],
                'enough'         => $enough ? : null,
            ];
        }
        return $info;
    }

    // 获取城市订单满减
    public static function getCityEnough($city_id)
    {
        $conf = [];
        $row = LihuaToolsConf::where(['city_id' => $city_id, 'type' => 1, 'status' => 1])->find();
        if ($row && $row['config'] && (!$row['end_date'] || $row['end_date'] >= date('Y-m-d'))) {
            $conf = json_decode($row['config'], true);
        }
        return $conf;
    }

    // 计算满减
    public static function countEnough($city_enough = [], $goods_amount = 0)
    {
        $data = ['name' => '', 'reach' => 0, 'reduce' => 0];
        if (is_array($city_enough) && $city_enough) {
            krsort($city_enough);
            foreach ($city_enough as $k => $v) {
                if ($goods_amount >= $k) {
                    $data = ['name' => "满{$k}元减{$v}元", 'reach' => $k, 'reduce' => $v];
                    break;
                }
            }
        }
        return $data;
    }

}
